#!/bin/bash
# Creates a ubuntu debian distribution package
# Input (optional): source directory, destination directory, version number
# Output: .deb package

# exit on error
set -e

echo "Creating ubuntu package..."

# clean everything
#cd ..
#qmake kisa.pro
#make release
#cd resources/

# set version to 1st input argument, or 0.63 as default value
VERSION=${1-"0.63"}

# set source dir to 2nd input argument, or trunk as default
SRC=${2-".."}

# set destination dir to 3rd input argument, or installs as default
DST=${3-"../../installs"}

# set different command line args
MKDIR_OPT="--verbose --parents"
CP_OPT="--verbose --preserve"
RM_OPT="--verbose --recursive --force"

TAR_OPT="--verbose --create --gzip"

if [[ -d ${DST}/ubuntu ]]; then
  rm ${RM_OPT} ${DST}/ubuntu/
fi

mkdir ${MKDIR_OPT} ${DST}/ubuntu/DEBIAN
mkdir ${MKDIR_OPT} ${DST}/ubuntu/usr/bin
mkdir ${MKDIR_OPT} ${DST}/ubuntu/usr/share/doc
mkdir ${MKDIR_OPT} ${DST}/ubuntu/usr/share/applications
mkdir ${MKDIR_OPT} ${DST}/ubuntu/usr/share/icons
mkdir ${MKDIR_OPT} ${DST}/ubuntu/usr/share/kisa

cp ${CP_OPT} ${SRC}/README ${DST}/ubuntu/usr/share/doc
cp ${CP_OPT} ${SRC}/COPYING ${DST}/ubuntu/usr/share/doc
cp ${CP_OPT} ${SRC}/ChangeLog ${DST}/ubuntu/usr/share/doc

cp ${CP_OPT} ${SRC}/bin/kisa ${DST}/ubuntu/usr/bin

cp ${CP_OPT} ${SRC}/kisa.desktop ${DST}/ubuntu/usr/share/applications
cp ${CP_OPT} ${SRC}/src/icons/kisa.png ${DST}/ubuntu/usr/share/icons
cp ${CP_OPT} ${SRC}/translations/*.qm ${DST}/ubuntu/usr/share/kisa

# get the total file size
SIZE=$(du --apparent-size --summarize ${DST}/ubuntu | awk '{print $1}')

# get the md5s
find ${DST}/ubuntu -type f | xargs md5sum > ${DST}/ubuntu/DEBIAN/md5sums

# the rest of the DEBIAN package files
cp ${CP_OPT} DEBIAN/* ${DST}/ubuntu/DEBIAN/

# replace the size
sed -i -e "s/Installed-Size:.*/Installed-Size: ${SIZE}/g" ${DST}/ubuntu/DEBIAN/control

cd ${DST}
sudo chown -R root ubuntu/
sudo chgrp -R root ubuntu/

# the Debian archived change log
tar --strip-components=4 ${TAR_OPT} --file=${DST}/ubuntu/usr/share/doc/ChangeLog.Debian.gz ${DST}/ubuntu/usr/share/doc/ChangeLog

# now create the package
FILENAME=kisa_${VERSION}_i686.deb
dpkg-deb --build ubuntu/ ${FILENAME}

# clean-up
# rm ${RM_OPT} ubuntu/

echo "Done"
echo "Package located at" $(pwd -P)/${FILENAME}
exit 0
